<template>
  <div class="f-select-category min-w-[200px] p-[10px]">
    <!-- 搜索 -->
    <div>
      <el-input v-model="params.title" class="w-full" clearable @clear="getCategory" @keyup.enter="getCategory" :placeholder="t('category.search.placeholder')">
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>
    <!-- 列表 -->
    <el-scrollbar class="mt-[10px]" max-height="800" distance="20" height="calc(100vh - 200px)" @end-reached="loadMoreList">
      <el-menu :default-active="String(active)" @select="handleSelect">
        <el-menu-item v-for="(item, index) in list" :index="String(item.id)" :key="index">
          <el-text truncated :type="item.hide == 1 ? 'info' : ''">{{item.title}}</el-text>
          <div v-permission:1009="$route.meta.auth" v-if="item.id !== 0" class="btn">
            <el-dropdown @command="handleCommand($event, item)">
                <el-icon><MoreFilled /></el-icon>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="1">{{ t('edit') }}</el-dropdown-item>
                  <el-dropdown-item command="5">{{ t('copy') }}</el-dropdown-item>
                  <el-dropdown-item command="4">绑定店铺</el-dropdown-item>
                  <el-dropdown-item command="3">分类标签</el-dropdown-item>
                  <div v-permission:1010="$route.meta.auth">
                    <el-dropdown-item command="2">{{ t('delete') }}</el-dropdown-item>
                  </div>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-menu-item>
      </el-menu>
      <!-- 加载状态指示器 -->
      <div v-if="isLoading" class="loading-indicator text-center py-2">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span class="ml-2">加载中...</span>
      </div>
    </el-scrollbar>
    <div v-permission:1011="$route.meta.auth" class="pt-[10px]">
      <el-button class="w-full block" type="primary" text @click="handleAdd"><el-icon><Plus /></el-icon>{{t('category.add')}}</el-button>
    </div>

    <!-- 复制 -->
    <f-form-model ref="copyFormRef" is="ActivityCopyForm" fullscreen width="1200" @change="getCategory"></f-form-model>
    <!-- 新建分类弹框 -->
    <f-form-model ref="formModelRef" is="CategoryForm" @change="getCategory"></f-form-model>
    <!-- 分类标签 -->
    <f-select-tag ref="labelModelRef" @change="handleSaveTag"></f-select-tag>
    <!-- 绑定店铺 -->
    <f-select-member ref="memberModelRef" :select-filter="selectFilter" :hide-content="hideContent" @change="handleBindConfirm">
      <template #search>
        <el-form-item label="绑定范围">
          <el-radio-group v-model="bindType" @change="handleBindTypeChange">
            <el-radio v-for="(item, index) in bindTypeList" :key="index" :label="item.label" :value="item.value"></el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
      <template #tree-icon="{ node }">
        <span v-if="node.data.is_dp == 1" class="mr-[5px] flex items-center">
          <el-icon v-if="node.expanded"><FolderOpened /></el-icon>
          <el-icon v-else><Folder /></el-icon>
        </span>
        <el-icon v-else class="mr-[5px]"><UserFilled /></el-icon>
      </template>
    </f-select-member>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { deleteCategoryApi, getActivityListApi, getCategoryListApi, getCategoryBindInfoApi, getCategoryTagInfoApi, getStoreTreeApi, setCategoryBindInfoApi } from '../../api'
import FFormModel from '../../components/f-form-model'
import FSelectTag from '../../components/f-select-tag/index.vue'
import FSelectMember from '../../components/f-select-member/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { t } from '@/lang'
import { filterTreeNode, forEachTree } from '../../utils/tree-tool'

const prop = defineProps({
    modelValue: {
        type: Number,
        default: 0
    }
})

const emit = defineEmits(['change', 'update:modelValue'])

const copyFormRef = ref()
const formModelRef = ref()
const labelModelRef = ref()
const memberModelRef = ref()
const storeTree = ref<ITreeItem[]>([])
const bindTypeList = ref<any[]>([
    {
        label: '全部可见',
        value: 0
    },
    {
        label: '按分组设置',
        value: 2,
        selection: []
    },
    {
        label: '按门店设置',
        value: 1,
        selection: []
    }
])
const bindType = ref(0)
const hideContent = computed(() => bindType.value == 0)

const list = ref<any[]>([])
const active = computed({
    get () {
        return prop.modelValue
    },
    set (value) {
        emit('update:modelValue', value)
    }
})

// const title = ref('')

/**
 * 获取分类列表
 */
const params = ref({
    page: 1,
    limit: 20,
    title: ''
})
const last_page = ref(0)
const isLoading = ref(false) // 加载状态
async function getCategory () {
    if (isLoading.value) return // 避免重复加载
    
    isLoading.value = true
    try {
        const res = await getCategoryListApi(params.value)
        last_page.value = res.data.last_page
        if (params.value.title) {
          list.value = res.data.data
        } else {
          if (params.value.page == 1) {
            list.value = [{ id: 0, title: t('category.all') }, ...res.data.data]
          } else {
              // 避免重复添加数据
              const newItems = res.data.data.filter(item => 
                  !list.value.some(existing => existing.id === item.id)
              )
              list.value.push(...newItems)
          }
        }
        
    } catch (error) {
        console.error('获取分类列表失败:', error)
    } finally {
        isLoading.value = false
    }
}

const loadMoreList = (direction: string) => {
  console.log(direction);
    if (isLoading.value) return
    if (direction === 'bottom' && last_page.value > params.value.page) {
      params.value.page++
      getCategory()
    }
}

/**
 * 新增
 */
function handleAdd () {
    formModelRef.value?.show(t('category.add'))
}

/**
 * 编辑
 * @param row
 */
function handleEdit (row: ICategoryItem) {
    formModelRef.value?.show(t('category.update'), row)
}

/**
 * 删除数据
 * @param row
 */
async function handleDelete (row: ICategoryItem) {
    const action = await ElMessageBox.alert(t('deleteTips'), t('alert.title'), {
        type: 'warning',
        showCancelButton: true,
        cancelButtonText: t('alert.cancel'),
        confirmButtonText: t('alert.confirm')
    })
    if (action === 'confirm') {
        await deleteCategoryApi(row.id)
        ElMessage.success(t('deleteSuccess'))
        getCategory()
    }
}

/**
 * 更多操作
 * @param value
 * @param row
 */
function handleCommand (value:String, row: ICategoryItem) {
    active.value = row.id!
    switch (value) {
        case '1':
            handleEdit(row)
            break
        case '2':
            handleDelete(row)
            break
        case '3':
            handleShowTag(row)
            break
        case '4':
            handleShowBindModel(row)
            break
        case '5':
            handleCopy(row)
            break
    }
}

function handleSelect (value:string) {
    active.value = Number(value)
    emit('change', value)
}

async function handleCopy (row: ICategoryItem) {
    const res = await getActivityListApi({
        page: 1,
        limit: 120,
        cate_id: row.id
    })
    if (res.data.data.length == 0) {
        ElMessage.warning('当前分类没有活动，请先添加活动')
        return
    }
    copyFormRef.value?.show('复制分类', res.data.data, 2, row)
}

async function getStoreTree () {
    const res = await getStoreTreeApi()
    // 遍历确定唯一key
    forEachTree(res.data, (item: ITreeItem) => {
        item.value = `${item.is_dp}_${item.value}`
    })
    if (bindType.value === 2) {
        storeTree.value = filterTreeNode(res.data, (node) => node.is_dp === 1)
    } else {
        storeTree.value = res.data
    }
    memberModelRef.value.setList(storeTree.value)
    memberModelRef.value.setSelection([])
}

const activeTree = ref<number[]>([])
async function handleShowBindModel (row: ICategoryItem) {
    // 获取绑定信息
    const res = await getCategoryBindInfoApi(row.id)
    activeTree.value = res.data.ids
    bindType.value = Number(res.data.model)
    // 获取门店树
    await getStoreTree()
    const selection:ITreeItem[] = []
    // 遍历确定唯一key
    forEachTree(storeTree.value, (item: ITreeItem) => {
      
        if (res.data.ids.includes(Number(item.value.split('_')[1])) && !item.children?.length) {
            selection.push(item)
        }
    })
    // 显示弹框
    memberModelRef.value?.show('绑定店铺', storeTree.value, selection)
}

function handleBindTypeChange () {
    if (bindType.value !== 0) {
        getStoreTree()
    }
}

function selectFilter (item: ITreeItem) {
    if (bindType.value === 2) {
        return true
    }
    return item.is_dp != 1
}
async function handleBindConfirm (value:ITreeItem[]) {
    console.log(bindType.value)
    console.log(value)
    const params = {
        model: bindType.value,
        ids: value.map(item => Number(item.value.split('_')[1]))
    }

    if (params.ids.length == 0 && activeTree.value.length || params.ids.length) {
      await setCategoryBindInfoApi(active.value, params)
      ElMessage.success('保存成功')
    }
    
}

// ====== 关联标签 =========

async function handleShowTag (row: ICategoryItem) {
    const res = await getCategoryTagInfoApi(row.id!)
    console.log(res.data.work)

    labelModelRef.value?.show('分类标签', res.data.work.map(item => item.id))
}

async function handleSaveTag (value: string[]) {
    await getCategoryTagInfoApi(active.value, {
        ids: value
    })
    ElMessage.success('保存成功')
}

onMounted(() => {
    getCategory()
    getStoreTree()
})
</script>

<style lang="scss" scoped>

.f-select-category {
  height: calc(100vh - 100px);
  position: sticky;
  top: 15px;
  right: 15px;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color);

  --el-menu-item-height: 40px;

  .el-scrollbar {
    flex: 1;
    overflow: hidden; /* 确保滚动条正常工作 */
    position: relative;
  }
  
  .loading-indicator {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }

  .el-menu {
    width: 100%;
    border:none
  }

  .el-menu-item {
    position: relative;
    padding-right: 30px;

    .btn {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      display: none;
      align-items: center;
      justify-content: center;
    }

    &.is-active {
      background-color: var(--el-color-primary-light-8);
      color: var(--el-color-primary);
      .btn {
        display: flex;
      }
    }

    &:hover {
      .btn {
        display: flex;
      }
    }
  }

}
</style>
